<?php

namespace App\Api\Controllers;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Api\Models\SystemConfigModel;
use App\Helper\DBRSAUtil;
use App\Api\Services\ContentTagsService;
use App\Api\Services\TextImageService;
use App\Api\Models\TextImageTemplatesModel;
use App\Api\Services\PictureEditingService;
use Illuminate\Support\Facades\Validator;
use App\Api\Models\ContentTagsModel;
use App\Api\Services\ImageLabelService;
use App\Api\Services\DispatchListService;
use App\Api\Models\DeliverGoodsModel;
use App\Api\Services\DeliverySlipService;
use App\Api\Models\DeliveryGoodsModel;
use App\Api\Services\QuotationNoService;
use App\Api\Models\QuotationGoodsModel;
use App\Api\Services\ReceiptService;
use App\Api\Services\MedicalDeliveryOrderService;
use App\Api\Models\MedicalProductsModel;
use App\Api\Services\MedicalDeliverOrderService;
use App\Api\Models\MedicalDeliverProductsModel;
use App\Api\Services\SealManageService;
class ContentTagsController extends Controller
{
     /**
     * 添加内容标签
     * @param pa_id        文字画册id
     * @param content_tags 标签名称
     * @param is_top       置顶
     * @param sort_number  排序数字     
     */
    public function addContentTags(Request $request){

        $res = SELF::loginCheck($request);
        
        if($res['code']==2){
            
            return response()->json($res); 
        }
        
         $data = $request->all();
         
        if(empty($request->input('pa_id'))){
            
            return response()->json(['code'=>1,'msg'=>'文字画册id，不能为空','data'=>'']);
        }
        
        if(isset($data['sort_number']) && !is_numeric($data['sort_number'])){
            
            return response()->json(['code'=>1,'msg'=>'排序字段，必须为数字','data'=>'']);
        }

    if(!empty($data['is_top']) && $data['is_top']==1){
            
            $condition['is_top']       = 1;
            $condition['pa_id']        = $request->input('pa_id');
            $condition['user_id']      = $res['data']['userId'];
            $condition['main_id']      = $res['data']['mainUserId'];
                        
            $info = ContentTagsService::getContentTagsInfo($condition);
            
            if(!empty($info)){
            
                ContentTagsService::updContentTags($condition, ['is_top'=>0]);
            }
        }
       
        $data['create_time']  = time();
        $data['user_id']      = $res['data']['userId'];
        $data['main_id']      = $res['data']['mainUserId'];        
        $data['pa_id']        = $request->input('pa_id');
        $data['is_top']       = empty($data['is_top'])?0:$data['is_top'];
        $data['sort_number']  = empty($data['sort_number'])?'':$data['sort_number'];
        $data['content_tags'] = empty($data['content_tags'])?'':$data['content_tags'];
        
        $id = ContentTagsService::addContentTags($data);
        
        if(!empty($id)){
            
            return response()->json(['code'=>0,'msg'=>'保存成功','data'=>['ct_id'=>$id]]);
         
        }else{
            return response()->json(['code'=>1,'msg'=>'保存失败','data'=>'']);
        }

    }
    
    /**
     * 查询内容标签关联内容模板列表
     * @param curr_page 当前页
     * @param page_size 显示个数
     * @param pa_id     文字画册id
     * @param sort_number 排序数字
     */
    public function getTagsRelationContentList(Request $request){
        
        $res = SELF::loginCheck($request);
        
        if($res['code']==2){
        
            return response()->json($res);
        }
        $currentPage = !empty($request->input('curr_page'))?$request->input('curr_page'):1;
        $pageSize    = !empty($request->input('page_size'))?$request->input('page_size'):20;
        
         $condition['user_id'] = $res['data']['userId']; 
         $condition['pa_id']   = $request->input('pa_id');
         $sort_number          = !empty($request->input('sort_number'))?$request->input('sort_number'):'';
        $list  = ContentTagsService::getContentTagsList($condition,$sort_number, $currentPage,$pageSize);        
       /*  echo "<pre>";
        var_dump($list);die; */        
        if(!empty($list['data'])){
            
            foreach ($list['data'] as $k=>$v){
                
              $tcondition['temp_tags_id'] = $v['id'];
              $tcondition['pa_id']        = $v['pa_id'];

              $tList=TextImageTemplatesModel::getContentTempLateList03($tcondition); 
              
              if(!empty($tList)){
                  
                  foreach ($tList as $tk=>$tv){
                      
                  $tList[$tk]['create_time']= date('Y-m-d H:i:s',$tv['create_time']);
                  $tList[$tk]['update_time']= date('Y-m-d H:i:s',$tv['update_time']);
                  
                  if (!empty($tv['temp_img_video_01'])){
                  
                      $tList[$tk]['temp_img_video_01']=explode(',', $tv['temp_img_video_01']);
                  }
                  
                  if (!empty($tv['temp_img_video_02'])){
                  
                      $tList[$tk]['temp_img_video_02']=explode(',', $tv['temp_img_video_02']);
                  }
                      
                  }
                  $list['data'][$k]['text_content_list'] = $tList;
                  
              }else{
                  
                  $list['data'][$k]['text_content_list'] = [];
              }
            }  
        }
        
        return response()->json(['code'=>0,'msg'=>'查询成功','data'=>$list]);
    }
   
    /**
     * 修改内容标签
     * @param ct_id        内容标签id
     * @param content_tags 标签名称
     * @param is_top       置顶
     * @param sort_number  排序数字
     */
    public function updContentTags(Request $request){
        
       if(empty($ctId = $request->input('ct_id'))){
           
         return response()->json(['code'=>1,'msg'=>'内容标签id,不能为空','data'=>'']);  
       }
       if(empty($paId = $request->input('pa_id'))){
            
           return response()->json(['code'=>1,'msg'=>'文字画册id,不能为空','data'=>'']);
       }
       $res = SELF::loginCheck($request);
       
       if($res['code']==2){
       
           return response()->json($res);
       }
       
       $condition['id']      = $ctId;
       $condition['user_id'] = $res['data']['userId'];

       $updData = $request->all();
       $updData['update_time']  = time();
       
       $updCondition['is_top']  = 1;
       $updCondition['pa_id']   = $paId;
       $updCondition['user_id'] = $res['data']['userId'];
       
       $info = ContentTagsService::getContentTagsInfo($updCondition);
        
       if(!empty($info)){
            
           if(isset($updData['is_top'])){
                
               if($updData['is_top'] == 1){
                    
                   ContentTagsService::updContentTags($updCondition,['is_top'=> 0]);
               }
           }
       }
       
       unset($updData['ct_id']);
       
       $bool = ContentTagsService::updContentTags($condition,$updData);
       
       if($bool){
       
           return response()->json(['code'=>0,'msg'=>'修改成功','data'=>'']);
       }
       
       return response()->json(['code'=>1,'msg'=>'修改失败','data'=>'']);
        
    }
    
    /**
     * 删除内容标签
     * @param ct_id 内容标签id
     */
    public function delContentTags(Request $request){
        
        if(empty($ctId = $request->input('ct_id'))){
             
            return response()->json(['code'=>1,'msg'=>'内容标签id,不能为空','data'=>'']);
        }
         
        $res = SELF::loginCheck($request);
         
        if($res['code']==2){
             
            return response()->json($res);
        }
         
        $condition['id'] = $ctId;
        $condition['user_id'] = $res['data']['userId'];
      
        $bool = ContentTagsService::delContentTags($condition);
        
        if($bool){
            
            return response()->json(['code'=>0,'msg'=>'删除成功','data'=>'']);
        }
        
            return response()->json(['code'=>1,'msg'=>'删除失败','data'=>'']);
        
    }
    
    /**
     * 查询内容标签信息
     * @param ct_id 内容标签id
     */
    public function getContentTagsInfo(Request $request){
        //参数验证
        $validator = Validator::make($data = $request->all(), [
            'ct_id'          => 'required'
        ],
            [
                'ct_id.required' => '缺少参数，内容标签id'
            ]);
        //参数错误响应
        if ($info = $validator->errors()->first()) {
    
            return response()->json(['code' => 1,'msg'  => $info,'data' => '']);
        }
    
        $condition['id']      = $data['ct_id'];
    
        $info = ContentTagsService::getContentTagsInfo($condition);
    
        if(!empty($info)){
            $tcondition['act.pa_id']   = $info['pa_id'];
            $tcondition['act.temp_tags_id']   = $data['ct_id'];
    
            $list = TextImageTemplatesModel::getContentTempLateList02($tcondition);
    
            if(!empty($list)){
                foreach ($list as $k=>$v){
                    $list[$k]['create_time'] =date('Y-m-d H:i:s',$v['create_time']);
                    $list[$k]['update_time'] =date('Y-m-d H:i:s',$v['update_time']);
                }
            }
            $info['content_temp_list']=$list;
             
            return response()->json(['code' =>0,'msg'  => '查询成功','data' => $info]);
        }else{
    
            return response()->json(['code' => 1,'msg'  => '查询失败','data' => '']);
        }
    
    }
   
    /**
     * 查询图片画册标签信息
     * @param label_id 内容标签id
     */
    public function getImageLabelInfo(Request $request){
        //参数验证
        $validator = Validator::make($data = $request->all(), [
            'label_id'          => 'required'
        ],
            [
                'label_id.required' => '缺少参数，内容标签id'
            ]);
        //参数错误响应
        if ($info = $validator->errors()->first()) {
    
            return response()->json(['code' => 1,'msg'  => $info,'data' => '']);
        }
    
        $condition['id']      = $data['label_id'];
    
        $info = ImageLabelService::getImageLabelInfo($condition);
    
        if(!empty($info)){
    
            if(!empty($info['Album_imgs'])){
    
                $info['Album_imgs'] = explode(',',$info['Album_imgs']);
            }
    
            $info['create_time'] = date('Y-m-d H:i:s',$info['create_time']);
            $info['update_time'] = date('Y-m-d H:i:s',$info['update_time']);
    
            return response()->json(['code' =>0,'msg'  => '查询成功','data' => $info]);
        }else{
    
            return response()->json(['code' => 1,'msg'  => '查询失败','data' => '']);
        }
    
    }
    /**
     * 查询图片画册信息
     * @param  pa_id 画册的id
     */
    public function getPictureAlbumInfo(Request $request){
         
        $validator = Validator::make(
            $data  = $request->all(), [
                'pa_id' =>'required'
            ],[
                'pa_id.required' => '画册的id,不能为空!'
            ]);
        //参数错误响应
        if ($info = $validator->errors()->first()) {
    
            return response()->json(['code' => 1,'msg' => $info,'data' => '']);
        }
    
        $condition['id']      = $data['pa_id'];
        
        $info = PictureEditingService::getPictureAlbumInfo($condition);
         
        if(empty($info)){
             
            return response()->json(['code' => 1,'msg' => '查询的图片画册，没有找到！','data' => '']);
        }
        $condition['pa_id']      = $data['pa_id'];
         
        unset($condition['id']);
       $iList = ImageLabelService::getImageLabelLists($condition);
       
       $info['label_data'] = [];
      
               if(!empty($iList)){
                   
                   $info['label_data'] = $iList;
                   
                   foreach ($info['label_data'] as $ik=>$iv){
                       
                       $info['label_data'][$ik]['id']         = $iv['id'];
                       $info['label_data'][$ik]['pa_id']      = $iv['pa_id'];
                       $info['label_data'][$ik]['label_name'] = $iv['label_name'];
                       
                       if(!empty($iv['Album_imgs'])){   
                           
                           $info['label_data'][$ik]['Album_imgs'] = explode(',',$iv['Album_imgs']);
                       }else{
                           $info['label_data'][$ik]['Album_imgs'] = [];
                       }
                   }
               }             
            $info['create_time'] =date('Y-m-d H:i:s',$info['create_time']);
            $info['update_time'] =date('Y-m-d H:i:s',$info['update_time']);
            return response()->json(['code' => 0,'msg' => '查询成功','data' => $info]);
    
    }
     /**
      * 查询文字画册信息
      * @param pa_id 文字画册id
      */
    public function getTextImageInfo(Request $request){
        //参数验证
        $validator = Validator::make($data = $request->all(), [
            'pa_id'          => 'required'
        ],
        [
            'pa_id.required' => '缺少参数，文字画册id'
        ]);
        //参数错误响应
        if ($info = $validator->errors()->first()) {
        
            return response()->json(['code' => 1,'msg'  => $info,'data' => '']);
        }
        
        $condition['id']      = $data['pa_id'];
        
        $info = TextImageService::getTextImageInfo($condition);
        
        if(!empty($info)){
            
            $tcondition['pa_id']   = $data['pa_id'];
            $tcondition['user_id'] = $info['user_id'];
            $list  = ContentTagsModel::getContentTagsList02($tcondition);
              
            if(!empty($list)){
            
                foreach ($list as $k=>$v){
                    unset($tcondition['user_id']);
                    $tcondition['temp_tags_id'] = $v['id'];
                    $tcondition['pa_id']        = $v['pa_id'];
            
                    $tList=TextImageTemplatesModel::getContentTempLateList03($tcondition);
            
                    if(!empty($tList)){
            
                        foreach ($tList as $tk=>$tv){
            
                            $tList[$tk]['create_time']= date('Y-m-d H:i:s',$tv['create_time']);
                            $tList[$tk]['update_time']= date('Y-m-d H:i:s',$tv['update_time']);
            
                            if (!empty($tv['temp_img_video_01'])){
            
                                $tList[$tk]['temp_img_video_01']=explode(',', $tv['temp_img_video_01']);
                            }
            
                            if (!empty($tv['temp_img_video_02'])){
            
                                $tList[$tk]['temp_img_video_02']=explode(',', $tv['temp_img_video_02']);
                            }
            
                        }
                        $list[$k]['text_content_list'] = $tList;
            
                    }else{
            
                        $list[$k]['text_content_list'] = [];
                    }
                }
            }

            $info['content_tags_list']=$list;
                       
            return response()->json(['code' =>0,'msg'  => '查询成功','data' => $info]);
        }else{
            
            return response()->json(['code' => 1,'msg'  => '查询失败','data' => '']);
        }
        
    }
    
    /**
     * 发货单号 （打印、分享，不用传token）
     * 
     * @param dispatch_id 发货单号id
     */
    public function dispatchListInfo(Request $request){
        //参数验证
        $validator = Validator::make($data = $request->all(), [
            'dispatch_id'       =>'required|integer',//发货单id
        ]);
        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return response()->json([
                'code' => 1,
                'msg'  => $info,
                'data' => '',
            ]);
        }
    
        $condition['id']      = $data['dispatch_id'];
      
        $info = DispatchListService::getDispatchListInfo($condition);
        $list = $info;
        if(!empty($info)){
    
            $list['goods_list']= DeliverGoodsModel::where(['dispatch_id'=>$info['id']])->get();
    
        }
        
        return response()->json([
            'code' => 0,
            'msg'  => 'success',
            'data' => $list,
        ]);
        
    }
    
    /**
     * 送货单信息（打印、分享，不用传token）
     * 
     * @param delivery_id 送货单号id
     */
    public function deliverySlipInfo(Request $request){
        //参数验证
        $validator = Validator::make($data = $request->all(), [
            'delivery_id'       =>'required|integer',//送货单id
        ]);
        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return response()->json([
                'code' => 1,
                'msg'  => $info,
                'data' => '',
            ]);
        }
    
        $condition['id']      = $data['delivery_id'];
       
        $info = DeliverySlipService::getDeliverySlipInfo($condition);
        $list = $info;
        if(!empty($info)){
    
            $list['goods_list']= DeliveryGoodsModel::where(['delivery_id'=>$info['id']])->get();    
        }
        return response()->json(['code' => 0,'msg'  => 'success','data' => $list]);
        
    }
    
    /**
     * 报价单信息（打印、分享，不用传token）
     * @param quotation_id
     */
    public function quotationNoInfo(Request $request){
        //参数验证
        $validator = Validator::make($data = $request->all(), [
            'quotation_id'       =>'required|integer',//报价单id
        ]);
        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return response()->json([
                'code' => 1,
                'msg'  => $info,
                'data' => '',
            ]);
        }
    
        $condition['id']      = $data['quotation_id'];
       
        $info = QuotationNoService::getQuotationNoInfo($condition);
        $list = $info;
        if(!empty($info)){
    
            $list['goods_list']= QuotationGoodsModel::where(['quotation_id'=>$info['id']])->get();
    
        }
        return response()->json(['code' => 0,'msg'  => 'success','data' => $list]);
        
    }
   
    /**
     * 收据信息（打印、分享，不用传token）
     * @param receipt_id
     */
    public function receiptInfo(Request $request){
        //参数验证
        $validator = Validator::make($data = $request->all(), [
            'receipt_id'       =>'required|integer',//收据id
        ]);
        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return response()->json([
                'code' => 1,
                'msg'  => $info,
                'data' => '',
            ]);
        }
    
        $condition['id'] = $data['receipt_id'];
      
    
        $info = ReceiptService::getReceiptInfo($condition);
        
        return response()->json(['code' => 0,'msg'  => 'success','data' => $info]);
        
    }
    
    /**
     * 医疗器械专用送货单信息（打印、分享，不用传token）
     * @param medical_delivery_id
     */
    public function medicalDeliveryInfo(Request $request){
        //参数验证
        $validator = Validator::make($data = $request->all(), [
            'medical_delivery_id'       =>'required|integer',//医疗器械专用送货单id
        ]);
        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return response()->json([
                'code' => 1,
                'msg'  => $info,
                'data' => '',
            ]);
        }
    
        $condition['id']      = $data['medical_delivery_id'];
          
        $info = MedicalDeliveryOrderService::getMedicalDeliveryOrderInfo($condition);
        $list = $info;
        if(!empty($info)){
    
            $list['goods_list']= MedicalProductsModel::where(['medical_delivery_id'=>$info['id']])->get();
    
        }
        
        return response()->json(['code' => 0,'msg'  => 'success','data' => $list]);        
    }
    
    /**
     * 医疗器械专用发货单信息（打印、分享，不用传token）
     * @param medical_deliver_id
     */
    public function medicalDeliverInfo(Request $request){
        //参数验证
        $validator = Validator::make($data = $request->all(), [
            'medical_deliver_id'       =>'required|integer',//医疗器械专用发货单id
        ]);
        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return response()->json([
                'code' => 1,
                'msg'  => $info,
                'data' => '',
            ]);
        }
    
        $condition['id'] = $data['medical_deliver_id'];
     
        $info = MedicalDeliverOrderService::getMedicalDeliverOrderInfo($condition);
        $list = $info;
        if(!empty($info)){
    
            $list['goods_list']= MedicalDeliverProductsModel::where(['medical_deliver_id'=>$info['id']])->get();
    
        }
            
        return response()->json(['code' => 0,'msg'  => 'success','data' => $list]);
    }
    
    
    /**
     * 印章信息（打印、分享，不用传token）
     * @param seal_id
     */
    public function sealInfo(Request $request){
        //参数验证
        $validator = Validator::make($data = $request->all(), [
            'seal_id'       =>'required|integer',//印章id
        ]);
        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return response()->json([
                'code' => 1,
                'msg'  => $info,
                'data' => '',
            ]);
        }
    
        $condition['id']      = $data['seal_id'];
        $info = SealManageService::getSealManageInfo($condition);
        
        return response()->json(['code' => 0,'msg'  => 'success','data' => $info]);
       
    }
    
    
    static public function loginCheck($request){
        
        $token = $request->header('token');
        
        if(empty($token)){
            
            return ['code' => 2,'msg' => 'token不能为空','data' => ''];
        }
        $array = explode(' ',$token);
        //私钥获取
        $private = SystemConfigModel::getConfigValue('private');
        $rsadata = DBRSAUtil::rsaDecrypt($array[1], $private);
        $rsadata = json_decode($rsadata,true);
        
        return ['code' => 0,'msg' => 'success','data' => $rsadata];
    }
}
